/* 第三方接口 */
const express = require("express");
const router = express.Router();
// var fs = require('fs');
var AipOcrClient = require("baidu-aip-sdk").ocr;
const mysql = require("mysql");

// 设置APPID/AK/SK
var APP_ID = "117184575";
var API_KEY = "s6OChfvy1RZvg263Gf1u76yM";
var SECRET_KEY = "ZZeMuRYEvXv7hKjGZuYtImdb7yXmDU54";
var client = new AipOcrClient(APP_ID, API_KEY, SECRET_KEY);

//设置连接池
const env = {
    host: "111.231.22.97",
    user: "wangs-others",
    password: "2xniGtbD6M4MWhJp",
    database: "wangs-others", //数据库名字
};



//调用百度智能云
//超过1000次 按量收费0.16元一次计划赠送十次然后每次收5毛
const getOthersImageTake = (req, res, url) => {
    client.generalBasicUrl(url).then(function (result) {
        res.send({
            code: 200,
            msg: 'success',
            data: {
                data: result['words_result'][0]['words']
            }
        })
    }).catch(function (err) {
        // 如果发生网络错误
        console.log(err);
    });
}
router.get('/getOthersImageTake', (req, res) => {
    const { url } = req.body
    //假设网络地址
    getOthersImageTake(req, res, url)
})



//调用第三方接口
//判断是否还有资源
//有就减1 返回true
const deterCall = (req) => {
    return new Promise((resolve, reject) => {
        const { user, form } = req.body
        let pool = mysql.createPool(env)
        pool.query('select * from deterUse where user = ? and form = ? ', [user, form], (err, result) => {
            if (err) {
                console.log(err)
                resolve({
                    allow: false,
                    msg: 'error'
                })
            }
            else {
                if (result.length > 0) {
                    //1到3预警 allow:true 大于3 true 0不可调用
                    switch (true) {
                        case result[0]['sum'] > 0 && result[0]['sum'] < 3: return resolve({ allow: true, msg: '预警:次数即将使用完,如需请充值', sum: result[0]['sum'] })
                        case result[0]['sum'] >= 3: return resolve({ allow: true, msg: 'success', sum: result[0]['sum'] })
                        case result[0]['sum'] == 0: return resolve({ allow: false, msg: '用户使用次数为0' })
                    }
                }
                else {
                    resolve({
                        allow: false,
                        msg: '此用户未开通权限'
                    })
                }
            }
        })
    })
}

//减去
const deleteCall = (user, sum, form) => {
    return new Promise((reslove, reject) => {
        let pool = mysql.createPool(env)
        let sums = sum - 1
        pool.query('update deterUse set sum = ? where user = ? and form = ? ', [sums, user, form], (err, resl) => {
            if (err) {
                console.log(err)
                resolve(false)
            }
            else {
                console.log(resl)
                if (resl.affectedRows >= 1) {
                    reslove(true)
                }
                else {
                    reslove(false)
                }
            }
        })
    })
}

const postDeterUser = async (req, res) => {
    //判断是否还有
    let deterCalls = await deterCall(req)
    if (deterCalls['allow']) {
        let deleteCalls = await deleteCall(req.body.user, deterCalls['sum'], req.body.form)
        console.log(deleteCalls, 'ppp')
        if (deleteCalls) {
            res.send({
                code: 200,
                msg: 'success'
            })
        }
        else {
            res.send({
                code: 500,
                msg: 'error'
            })
        }

    }
    else {
        res.send({
            code: 500,
            msg: deterCalls['msg']
        })
    }

}
router.post('/postDeterUser', (req, res) => {
    postDeterUser(req, res)
})



//用户开通权限
//判断表里是否有
const isUserForm = (req) => {
    let { user, form } = req.body
    return new Promise((reslove, reject) => {
        let pool = mysql.createPool(env)
        let sql = 'select * from deterUse where user = ? and form = ?'
        pool.query(sql, [user, form], (err, resk) => {
            try {
                if (resk.length > 0) {
                    reslove(false)
                }
                else {
                    reslove(true)
                }

            } catch {
                //打印error错误
                console.log(err)
            }
        })
    })
}

const addUserForm = (req) => {
    return new Promise((reslove, reject) => {
        let { user, form, time, remark } = req.body
        let pool = mysql.createPool(env)
        pool.query('insert into deterUse values(?,?,?,?,?)', [user, form, time, '0', remark], (err, reso) => {
            try {
                if (reso.affectedRows >= 1) {
                    reslove(true)
                }
                else {
                    reslove(false)
                }
            } catch {
                console.log(err, 'error')
            }
        })
    })
}

const openPremission = async (req, res) => {
    let isUserForms = await isUserForm(req)
    if (isUserForms) {
        let addUserForms = await addUserForm(req)
        if (addUserForms) {
            res.send({
                code: 200,
                msg: 'success'
            })
        }
        else {
            res.send({
                code: 500,
                msg: "error"
            })

        }
    }
    else {
        res.send({
            code: 500,
            msg: '用户已存在'
        })
    }

}
router.post('/openPremission', (req, res) => {
    openPremission(req, res)
})


module.exports = router;